package com.atguigu.sparsearray;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;

/*
稀疏数组，对数组进行压缩
 */
public class SparseArray {

    public static void main(String[] args) throws Exception {
        //定义一个二维数组
        int arr[][] = new int[11][12];
        arr[0][2] = 1;
        arr[1][3] = 2;
        arr[3][7] = 1;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
            System.out.println();
        }

        //将二维数组转换为稀疏数组
        int sum = 0;
        for(int a=0;a<arr.length;a++){
            for (int b=0;b<arr[a].length;b++){
                if (arr[a][b] != 0){
                    sum++;
                }
            }
        }

        //定义稀疏数组
        int arry1[][] = new int[sum+1][3];
        arry1[0][0] = arr.length;
        arry1[0][1] = arr[0].length;
        arry1[0][2] = sum;

        int cun = 0;
        for(int a=0;a<arr.length;a++){
            for (int b=0;b<arr[a].length;b++){
                if (arr[a][b] != 0){
                    cun++;
                    arry1[cun][0]=a;
                    arry1[cun][1]=b;
                    arry1[cun][2]=arr[a][b];
                }
            }
        }

        //打印数组
        for (int[] ints : arry1) {
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
            System.out.println();
        }





        //将稀疏数组转化为二维数组

        int arry2[][] = new int[arry1[0][0]][arry1[0][1]];
        for(int i=1;i<arry1.length;i++){
            arry2[arry1[i][0]][arry1[i][1]] = arry1[i][2];
        }

        for (int[] ints : arry2) {
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
            System.out.println();
        }

    }


}
